var express = require('express');
var router = express.Router();
const { getList, getDetail, newBlog, updateBlog, deleteBlog } = require('../controller/blogController');
const { SuccessModel, ErrorModel } = require('../model/resModel')
const loginCheck = require('../midclleware/loginCheck')

/* GET home page. */
router.get('/list', function (req, res, next) {
  let author = req.query.author || '';
  const keyword = req.query.keyword || '';
  // 管理员验证
  const relust = getList(author, keyword);

  return relust.then((listData) => {
    res.json(new SuccessModel(listData));
  })

});

router.get('/detail', function (req, res, next) {
  const result = getDetail(req.query.id);
  return result.then(data => {
    res.json(new SuccessModel(data))
  })

});
//新建一篇
router.post('/new', loginCheck, function (req, res, next) {
  req.body.author = req.session.username;
  const result = newBlog(req.body);
  return result.then(data => {
    res.json(new SuccessModel(data))
  })
});
//更新一篇
router.post('/update', loginCheck, function (req, res, next) {
  const id = req.query.id;
  const updateFlg = updateBlog(id, req.body)

  return updateFlg.then(flg => {
    if (flg) {
      res.json(new SuccessModel(flg))
    } else {
      res.json(new ErrorModel("更新博客内容失败"))
    }
  })
});
router.post('/del', loginCheck, function (req, res, next) {
  const id = req.query.id;
  const author = req.session.username;
  const deleteFlg = deleteBlog(id, author);
  return deleteFlg.then(val => {
    if (val) {
      res.json(new SuccessModel(val));
    } else {
      res.json(new ErrorModel("删除博客失败"))
    }

  })
});

module.exports = router;
